package com.hyjx.framework.service;

import com.hyjx.framework.common.Constants;
import com.hyjx.framework.common.tree.TreeObject;
import com.hyjx.framework.common.tree.TreeUtil;
import com.hyjx.framework.common.tree.ZTreeNode;
import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.component.field.ExtField;
import com.hyjx.framework.component.field.ExtFieldService;
import com.hyjx.framework.orm.dao.IBaseDao;
import com.hyjx.framework.service.model.CacheMenu;
import com.hyjx.framework.service.model.CacheOrg;
import com.hyjx.framework.service.model.CacheRole;
import com.hyjx.framework.service.model.CacheSubSys;
import com.hyjx.framework.service.model.CacheUser;
import com.hyjx.framework.uc.admin.AdminModel;
import com.hyjx.framework.uc.admin.AdminService;
import com.hyjx.framework.uc.depart.DepartModel;
import com.hyjx.framework.uc.depart.DepartService;
import com.hyjx.framework.uc.menu.MenuFunc;
import com.hyjx.framework.uc.menu.MenuModel;
import com.hyjx.framework.uc.menu.MenuService;
import com.hyjx.framework.uc.role.RoleMenuModel;
import com.hyjx.framework.uc.role.RoleModel;
import com.hyjx.framework.uc.role.RoleOrgModel;
import com.hyjx.framework.uc.role.RoleService;
import com.hyjx.framework.uc.subsys.SubsysModel;
import com.hyjx.framework.uc.subsys.SubsysService;
import com.hyjx.framework.uc.user.UserModel;
import com.hyjx.framework.uc.user.UserRoleModel;
import com.hyjx.framework.uc.user.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限相关缓存管理
 *
 * @author peter
 */
public class RightManager {
    private static final Log logger = LogFactory.getLog(RightManager.class);
    
    /**
     * 初始化缓存数据
     */
    public static void init(int which) {
        init();
    }
    
    /**
     * 初始化缓存数据
     */
    public static void init() {
        logger.info(StringHelper.getDateTimeMill() + " 正在初始化权限缓存");
        initOrg();
        initSysMenu();
        initRole();
        initUser();
        logger.info(StringHelper.getDateTimeMill() + " 初始化权限缓存结束");
    }
    
    /**
     * 缓存单位、部门
     */
    public static void initOrg() {
        DepartService deptSrv = (DepartService) SpringBeanUtil.getBean(Constants.DEPART_SERVICE_NAME);
        List<DepartModel> list = deptSrv.getAllDepart(new DepartModel());
        CacheService.set("sys.right.allorgdepts", list);
        DepartModel rootOrg = null;
        
        Map<String, Map<String, String>> extDepartMap = getExtDataByTable("sys_right_depart", "DEPART_CODE");
        Map<String, CacheOrg> orgs = new LinkedHashMap<String, CacheOrg>();
        for (DepartModel model : list) {
            if ("#".equals(model.getDepart_parent_code())) {
                if (rootOrg == null) {
                    rootOrg = model;
                }
            }
            
            Map<String, String> extData = extDepartMap.get(model.getDepart_code());
            model.setExtData(extData);
            if ("1".equals(model.getDepart_type())) {
                String orgCode = model.getDepart_code();
                
                Map<String, DepartModel> depts = new LinkedHashMap<String, DepartModel>();
                for (DepartModel dept : list) {
                    if ("0".equals(dept.getDepart_type())) {
                        if (orgCode.equals(dept.getOrg_code())) {
                            depts.put(dept.getDepart_code(), dept);
                        }
                    }
                }
                CacheOrg org = new CacheOrg(orgCode, model, depts);
                orgs.put(orgCode, org);
            }
        }
        CacheService.set("sys.right.allorgs", orgs);
        if (rootOrg == null){
            throw new RuntimeException("部门信息配置错误，无根元素");
        }
        CacheService.set("sys.right.rootorg", rootOrg);
        
        Map<String, DepartModel> departs = new LinkedHashMap<String, DepartModel>();
        Map<String, DepartModel> allorgdeptsmap = new LinkedHashMap<String, DepartModel>();
        for (DepartModel dept : list) {
            if ("0".equals(dept.getDepart_type())) {
                departs.put(dept.getDepart_code(), dept);
            }
            allorgdeptsmap.put(dept.getDepart_code(), dept);
        }
        CacheService.set("sys.right.alldeparts", departs);
        CacheService.set("sys.right.allorgdeptsmap", allorgdeptsmap);
    }
    
    /**
     * 查询扩展信息
     *
     * @param tableName
     * @return
     */
    private static Map<String, Map<String, String>> getExtDataByTable(String tableName, String pkName) {
        ExtFieldService extFieldService = (ExtFieldService) SpringBeanUtil.getBean("extFieldServiceImpl");
        List<ExtField> fields = extFieldService.getFieldsByTableName(tableName);//查出所有扩展字段
        IBaseDao baseDao = (IBaseDao) SpringBeanUtil.getBean("baseDao");
        
        String sql = "select " + pkName;
        for (int i = 0; i < fields.size(); i++) {
            sql += "," + fields.get(i).getEnName();
        }
        sql += " from " + tableName;
        List<Map<String, Object>> list = baseDao.queryListBySql(sql);
        
        Map<String, Map<String, String>> result = new LinkedHashMap<String, Map<String, String>>();
        for (Map<String, Object> map : list) {
            Map<String, String> extData = new LinkedHashMap<String, String>();
            
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                Object ov = entry.getValue();
                if (ov == null) {
                    extData.put(entry.getKey(), "");
                } else {
                    extData.put(entry.getKey(), ov.toString());
                }
            }
            result.put(map.get(pkName).toString(), extData);
        }
        return result;
    }
    
    /**
     * 缓存子系统、菜单、操作
     */
    public static void initSysMenu() {
        SubsysService subsysSrv = (SubsysService) SpringBeanUtil.getBean("subsysServiceImpl");
        List<SubsysModel> list = subsysSrv.getAllSubsys(new SubsysModel());
        MenuService menuSrv = (MenuService) SpringBeanUtil.getBean("menuServiceImpl");
        MenuModel queryMenu = new MenuModel();
        queryMenu.setValidity("Y");
        List<MenuModel> menuList = menuSrv.getMenuList(queryMenu);
        List<MenuFunc> funcList = menuSrv.selectFuncList(new MenuFunc());
        
        Map<String, CacheSubSys> subsyses = new LinkedHashMap<String, CacheSubSys>();
        Map<String, SubsysModel> codesubsys = new LinkedHashMap<String, SubsysModel>();
        
        Collections.sort(menuList);
        for (SubsysModel model : list) {
            codesubsys.put(model.getSubsys_code(), model);
            String sysId = model.getSubsys_id();
            Map<String, CacheMenu> menus = new LinkedHashMap<String, CacheMenu>();
            for (MenuModel menu : menuList) {
                if (sysId.equals(menu.getSubsys_id())) {
                    Map<String, MenuFunc> operates = new LinkedHashMap<String, MenuFunc>();
                    String menuCode = menu.getMenu_code();
                    for (MenuFunc operate : funcList) {
                        if (menuCode.equals(operate.getMenu_code())) {
                            operates.put(operate.getOperate_id(), operate);
                        }
                    }
                    menus.put(menuCode, new CacheMenu(menuCode, menu, operates));
                    
                }
            }
            CacheSubSys subsys = new CacheSubSys(sysId, model, menus);
            subsyses.put(sysId, subsys);
        }
        CacheService.set("sys.right.allsubsys", subsyses);
        
        CacheService.set("sys.right.codesubsys", codesubsys);
        
        Map<String, MenuModel> allmenus = new LinkedHashMap<String, MenuModel>();
        for (MenuModel menu : menuList) {
            allmenus.put(menu.getMenu_code(), menu);
        }
        CacheService.set("sys.right.allmenus", allmenus);
        
        Map<String, MenuFunc> alloperates = new LinkedHashMap<String, MenuFunc>();
        for (MenuFunc func : funcList) {
            alloperates.put(func.getOperate_id(), func);
        }
        CacheService.set("sys.right.alloperates", alloperates);
    }
    
    /**
     * 缓存角色、角色对应单位、角色对应菜单、角色对应操作
     */
    public static void initRole() {
        RoleService roleSrv = (RoleService) SpringBeanUtil.getBean("roleServiceImpl");
        List<RoleModel> list = roleSrv.queryAllRoles();
        List<RoleOrgModel> orglist = roleSrv.queryAllRoleOrgList();
        List<RoleMenuModel> menulist = roleSrv.queryAllRoleMenuList();
        
        UserService userSrv = (UserService) SpringBeanUtil.getBean("userServiceImpl");
        List<UserRoleModel> roleList = userSrv.queryAllUserRoleList();
        Map<String, CacheRole> roles = new LinkedHashMap<String, CacheRole>();
        for (RoleModel model : list) {
            String roleId = model.getRole_id();
            
            CacheRole role = new CacheRole(roleId, model);
            Map<String, RoleOrgModel> roleorgs = new LinkedHashMap<String, RoleOrgModel>();
            for (RoleOrgModel ro : orglist) {
                if (roleId.equals(ro.getRole_id())) {
                    roleorgs.put(ro.getOrg_code(), ro);
                }
            }
            role.setRoleorgs(roleorgs);
            
            Map<String, RoleMenuModel> rolemenus = new LinkedHashMap<String, RoleMenuModel>();
            for (RoleMenuModel rm : menulist) {
                if (roleId.equals(rm.getRole_id())) {
                    rolemenus.put(rm.getMenu_code(), rm);
                }
            }
            role.setRolemenus(rolemenus);
            String userIds = ",";
            for (UserRoleModel ur : roleList) {
                if (roleId.equals(ur.getRole_id())) {
                    userIds += ur.getUser_id() + ",";
                }
            }
            role.setUserIds(userIds);
            roles.put(roleId, role);
        }
        CacheService.set("sys.right.allroles", roles);
    }
    
    /**
     * 缓存用户、用户对应角色、用户实际的功能权限、数据权限
     */
    public static void initUser() {
        UserService userSrv = (UserService) SpringBeanUtil.getBean("userServiceImpl");
        List<UserModel> list = userSrv.getAllUsers();
        AdminService adminSrv = (AdminService) SpringBeanUtil.getBean("adminServiceImpl");
        List<AdminModel> adminList = adminSrv.getAllAdmins();
        Map<String, Map<String, String>> extMap = getExtDataByTable("sys_right_user", "USER_ID");
        if (adminList != null) {
            for (AdminModel admin : adminList) {
                UserModel um = new UserModel();
                um.setUser_id(admin.getAdmin_id());
                um.setUser_account(admin.getAdmin_account());
                um.setUser_pwd(admin.getAdmin_pwd());
                um.setUser_name(admin.getAdmin_name());
                um.setUserIsAdmin("1");
                um.setSuperAdmin(true);
                um.setValidity("Y");
                String rootOrgCode = RightManager.getRootOrg().getDepart_code();
                um.setOrg_code(rootOrgCode);
                um.setDepart_code(rootOrgCode);
                list.add(um);
            }
        }
        List<UserRoleModel> roleList = userSrv.queryAllUserRoleList();
        Map<String, CacheRole> sysRoles = RightManager.getSysRoles();
        Map<String, MenuModel> allMenus = RightManager.getAllMenus();
        
        
        Map<String, MenuFunc> allOperates = RightManager.getAllOperates();
        Map<String, CacheUser> users = new LinkedHashMap<String, CacheUser>();
        Map<String, CacheUser> userAccounts = new LinkedHashMap<String, CacheUser>();
        boolean flag = false;
        for (UserModel model : list) {
            String userId = model.getUser_id();
            if (flag && "1".equals(model.getUserIsAdmin())) continue; //解决多个管理员菜单重复问题
            if ("1".equals(model.getUserIsAdmin())) {
                flag = true;
            }
            Map<String, String> extData = extMap.get(model.getUser_id());
            model.setExtData(extData);
            
            Map<String, UserRoleModel> userroles = new LinkedHashMap<String, UserRoleModel>();
            //4个临时map,先将每用户所对应的子系统/菜单/操作求并
            Map<String, String> rightsubsys = new LinkedHashMap<String, String>();
            Map<String, MenuModel> rightmenus = new LinkedHashMap<String, MenuModel>();    //一级菜单
            Map<String, MenuModel> rightmenus2 = new LinkedHashMap<String, MenuModel>();    //非一级菜单
            Map<String, MenuFunc> rightoperates = new LinkedHashMap<String, MenuFunc>();
            
            for (UserRoleModel ur : roleList) {
                if (userId.equals(ur.getUser_id())) {
                    String roleId = ur.getRole_id();
                    CacheRole cacheRole = sysRoles.get(roleId);
                    if (cacheRole == null) {
                        continue;
                    }
                    
                    userroles.put(roleId, ur);
                    Map<String, RoleMenuModel> rolemenus = cacheRole.getRolemenus();
                    for (RoleMenuModel rm : rolemenus.values()) {
                        String menuCode = rm.getMenu_code();
                        if ("1".equals(rm.getMenutype())) {
                            if (!rightsubsys.containsKey(rm.getMenu_code())) {
                                rightsubsys.put(menuCode, menuCode);
                            }
                        } else if ("2".equals(rm.getMenutype())) {
                            MenuModel mm = allMenus.get(menuCode);
                            
                            if (mm == null) {
                                continue;
                            }
                            if ("#".equals(mm.getMenu_parent_code())) {
                                if (!rightmenus.containsKey(menuCode)) {
                                    try {
                                        MenuModel newMenu = (MenuModel) BeanUtils.cloneBean(mm);
                                        rightmenus.put(menuCode, newMenu);
                                    } catch (Exception ex) {
                                    
                                    }
                                }
                            } else {
                                if (!rightmenus2.containsKey(menuCode)) {
                                    try {
                                        MenuModel newMenu = (MenuModel) BeanUtils.cloneBean(mm);
                                        rightmenus2.put(menuCode, newMenu);
                                    } catch (Exception ex) {
                                    
                                    }
                                }
                            }
                        } else if ("3".equals(rm.getMenutype())) {
                            if (!rightoperates.containsKey(menuCode)) {
                                rightoperates.put(menuCode, allOperates.get(menuCode));
                            }
                        }
                    }
                }
            }
            
            //初始化用户权限信息
            CacheUser user = calcUserRight(userId, model, userroles, rightsubsys, rightmenus, rightmenus2, rightoperates);
            users.put(userId, user);
            userAccounts.put(user.getUser().getUser_account(), user);
        }
        CacheService.set("sys.right.allusers", users);
        CacheService.set("sys.right.alluseraccounts", userAccounts);
    }
    
    /**
     * 计算用户的权限
     *
     * @param userId
     * @param model
     * @param userroles
     * @param rightsubsys
     * @param rightmenus
     * @param rightmenus2
     * @param rightoperates
     */
    private static CacheUser calcUserRight(String userId, UserModel model, Map<String, UserRoleModel> userroles, Map<String, String> rightsubsys, Map<String, MenuModel> rightmenus, Map<String, MenuModel> rightmenus2, Map<String, MenuFunc> rightoperates) {
        CacheUser user = new CacheUser(userId, model, userroles);

        Map<String, List<MenuModel>> rightMap = new LinkedHashMap<String, List<MenuModel>>();
        if (model.isSuperAdmin()) {
            //超级管理员的特殊处理
            Map<String, CacheSubSys> sysMenus = getSysMenus();
            for (CacheSubSys cs : sysMenus.values()) {
                String subsysId = cs.getSubSysId();
                List<MenuModel> menus = new ArrayList<MenuModel>();
                Map<String, CacheMenu> csMenus = cs.getMenus();
                Map<String, MenuModel> processedMap = new LinkedHashMap<String, MenuModel>();
                for (CacheMenu cm : csMenus.values()) {
                    //System.out.println(cm.getMenu().getMenu_name());
                    MenuModel mm = cm.getMenu();
                    if ("#".equals(mm.getMenu_parent_code())) {
                        MenuModel newModel = cloneMenu(mm);
                        menus.add(newModel);
                        processedMap.put(newModel.getLevelId(), newModel);
                    } else {
                        //此处菜单levelid必须3位以上
                        String firstLevelId = mm.getLevelId().substring(0, 6);
                        if (processedMap.get(firstLevelId) != null) {
                            processedMap.get(firstLevelId).getChildren().add(mm);
                        }
                    }
                }
                Collections.sort(menus);
                rightMap.put(subsysId, menus);
            }
            user.setRightMenuMap(rightMap);
            List<MenuModel> list = rightMap.get("console");
//			for(MenuModel mm : list)
//			{
//				for(MenuModel mm2 : mm.getChildren())
//				{
//					System.out.println(mm.getMenu_name()+"//"+mm2.getMenu_name());
//				}
//			}
        } else {
            for (String subsysId : rightsubsys.keySet()) {
                List<MenuModel> menus = new ArrayList<MenuModel>();
                for (MenuModel mm1 : rightmenus.values()) {
                    if (subsysId.equals(mm1.getSubsys_id())) {
                        List<MenuModel> children = new ArrayList<MenuModel>();
                        for (MenuModel mm2 : rightmenus2.values()) {
                            if (mm2.getLevelId().startsWith(mm1.getLevelId())) {
                                List<MenuFunc> operates2 = new ArrayList<MenuFunc>();
                                for (MenuFunc mf2 : rightoperates.values()) {
                                    if (mf2 == null) {
                                        continue;
                                    }
                                    if (mm2.getMenu_code().equals(mf2.getMenu_code())) {
                                        operates2.add(mf2);
                                    }
                                }
                                mm2.setOperates(operates2);
                                children.add(mm2);
                            }
                        }
                        Collections.sort(children);
                        MenuModel cloneMenu = cloneMenu(mm1);
                        cloneMenu.setChildren(children);
                        
                        List<MenuFunc> operates = new ArrayList<MenuFunc>();
                        for (MenuFunc mf : rightoperates.values()) {
                            if (mf == null)
                                continue;
                            if (cloneMenu.getMenu_code().equals(mf.getMenu_code())) {
                                operates.add(mf);
                            }
                        }
                        cloneMenu.setOperates(operates);
                        menus.add(cloneMenu);
                    }
                }
                Collections.sort(menus);
                rightMap.put(subsysId, menus);
            }
        }
        user.setRightMenuMap(rightMap);
        return user;
    }
    
    /**
     * 克隆 MenuModel 对象
     *
     * @return
     */
    private static MenuModel cloneMenu(MenuModel model) {
        MenuModel newMenu = null;
        try {
            newMenu = (MenuModel) BeanUtils.cloneBean(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newMenu;
    }
    
    /**
     * 取单位缓存数据
     */
    public static Map<String, CacheOrg> getSysOrgs() {
        return (Map<String, CacheOrg>) CacheService.get("sys.right.allorgs");
    }
    
    /**
     * 取单位缓存数据
     */
    public static DepartModel getRootOrg() {
        return (DepartModel) CacheService.get("sys.right.rootorg");
    }
    
    /**
     * 取部门缓存数据
     */
    public static Map<String, DepartModel> getSysDeparts() {
        return (Map<String, DepartModel>) CacheService.get("sys.right.alldeparts");
    }
    
    /**
     * 取子系统、菜单、操作的缓存数据
     */
    public static Map<String, CacheSubSys> getSysMenus() {
        return (Map<String, CacheSubSys>) CacheService.get("sys.right.allsubsys");
    }
    
    /**
     * 取子系统、菜单、操作的缓存数据
     */
    public static SubsysModel getSubsysByCode(String code) {
        Map<String, SubsysModel> codesubsys = (Map<String, SubsysModel>) CacheService.get("sys.right.codesubsys");
        return codesubsys.get(code);
    }
    
    /**
     * 取所有可用的菜单信息
     */
    public static Map<String, MenuModel> getAllMenus() {
        return (Map<String, MenuModel>) CacheService.get("sys.right.allmenus");
    }
    
    /**
     * 取所有操作信息
     */
    public static Map<String, MenuFunc> getAllOperates() {
        return (Map<String, MenuFunc>) CacheService.get("sys.right.alloperates");
    }
    
    /**
     * 取角色缓存数据
     */
    public static Map<String, CacheRole> getSysRoles() {
        return (Map<String, CacheRole>) CacheService.get("sys.right.allroles");
    }
    
    /**
     * 取用户缓存数据
     */
    public static Map<String, CacheUser> getSysUsers() {
        return (Map<String, CacheUser>) CacheService.get("sys.right.allusers");
    }
    
    /**
     * 取用户缓存数据
     */
    public static Map<String, CacheUser> getSysUserAccounts() {
        return (Map<String, CacheUser>) CacheService.get("sys.right.alluseraccounts");
    }
    
    /**
     * 从缓存中取当前用户信息
     */
    public static CacheUser getCurrUserRelaInfoById(String userId) {
        return ((Map<String, CacheUser>) CacheService.get("sys.right.allusers")).get(userId);
    }
    
    /**
     * 取用户权限单位编码
     *
     * @param userOrgCode 用户所属单位编码
     * @return 用户权限单位编码
     */
    public static String getUserDataOrgCode(String userOrgCode) {
        
        DepartModel org = getDepartByCode(userOrgCode);
        if (org == null) {
            logger.info("指定的单位代码在缓存中不存在：");
            logger.info(userOrgCode);
            return null;
        }
        if ("1".equals(org.getDepart_type()))
            return org.getDepart_code();
        String pCode = org.getDepart_parent_code();
        if (pCode == null || "".equals(pCode) || "#".equals(pCode)) {
            return userOrgCode;
        }
        
        return getUserDataOrgCode(pCode);
//		DepartModel parentOrg = getDepartByCode(pCode);
//		if(parentOrg==null){
//			return userOrgCode;
//		}else{
//			if(org.getDepart_level().equals(parentOrg.getDepart_level())){
//				return pCode;
//			}else{
//				return userOrgCode;
//			}
//		}
    }
    
    /**
     * 根据单位编码取单位信息，取自缓存
     *
     * @param orgCode 单位编码
     * @return
     */
    public static DepartModel getOrgByCode(String orgCode) {
        return getDepartByCode(orgCode);
    }
    
    /**
     * 根据部门编码取部门信息，取自缓存
     *
     * @param departCode 部门编码
     * @return
     */
    public static DepartModel getDepartByCode(String departCode) {
        Map<String, DepartModel> allOrgDepartsMap = getAllOrgDepartsMap();
        return allOrgDepartsMap.get(departCode);
    }
    
    /**
     * 根据单位编码取名称，取自缓存
     *
     * @param orgCode 单位编码
     * @return
     */
    public static String getOrgNameByCode(String orgCode) {
        DepartModel model = getDepartByCode(orgCode);
        if (model == null) {
            return "";
        } else {
            return model.getDepart_name();
        }
    }
    
    /**
     * 取用户对应的数据权限串
     *
     * @param userId
     * @return
     */
    public static String getUserOrgs(String userId) {
        Map<String, UserRoleModel> map = getSysUsers().get(userId).getUserroles();
        Map<String, CacheRole> roleMap = getSysRoles();
        Map<String, String> allOrgs = new HashMap<String, String>();
        
        //排重
        for (String roleId : map.keySet()) {
            Map<String, RoleOrgModel> roleorgs = roleMap.get(roleId).getRoleorgs();
            for (String orgCode : roleorgs.keySet()) {
                allOrgs.put(orgCode, orgCode);
            }
        }
        //串
        StringBuffer sb = new StringBuffer();
        sb.append(",");
        for (String orgCode : allOrgs.keySet()) {
            sb.append(orgCode + ",");
        }
        
        return sb.toString();
    }
    
    /**
     * 取用户对应的功能权限串
     *
     * @param userId
     * @return 菜单字符串，以英文逗号分隔。
     */
    public static String getUserMenus(String userId) {
        Map<String, UserRoleModel> map = getSysUsers().get(userId).getUserroles();
        Map<String, CacheRole> roleMap = getSysRoles();
        Map<String, String> allMenus = new HashMap<String, String>();
        
        //排重
        for (String roleId : map.keySet()) {
            Map<String, RoleMenuModel> rolemenus = roleMap.get(roleId).getRolemenus();
            for (String menuCode : rolemenus.keySet()) {
                allMenus.put(menuCode, menuCode);
            }
        }
        //串
        StringBuffer sb = new StringBuffer();
        sb.append(",");
        for (String orgCode : allMenus.keySet()) {
            sb.append(orgCode + ",");
        }
        
        return sb.toString();
    }
    
    /**
     * 根据单位代码取所有上级单位代码
     *
     * @param orgCode 单位代码
     * @return 单位代码串
     */
    public static String getOrgAllSuperCodes(String orgCode) {
        if (orgCode != null && !"".equals(orgCode)) {
            return "";
        }
        
        StringBuffer sb = new StringBuffer();
        Map<String, CacheOrg> orgMap = getSysOrgs();
        String currentCode = orgCode;
        while (true) {
            CacheOrg org = orgMap.get(currentCode);
            //todo
            String pCode = org.getOrg().getDepart_parent_code();
            if (pCode == null || "".equals(pCode)) {
                break;
            } else {
                if (sb.length() == 0) {
                    sb.append("'" + pCode + "'");
                } else {
                    sb.append(",'" + pCode + "'");
                }
                currentCode = pCode;
            }
        }
        return sb.toString();
    }
    
    /**
     * 取所有子系统数据
     */
    public static List<SubsysModel> getAllSubsys() {
        Map<String, CacheSubSys> map = (Map<String, CacheSubSys>) CacheService.get("sys.right.allsubsys");
        List<SubsysModel> list = new ArrayList<SubsysModel>();
        for (CacheSubSys model : map.values()) {
            list.add(model.getSubSys());
        }
        return list;
    }
    
    /**
     * 取所有depart表数据
     *
     * @return
     */
    public static List<DepartModel> getAllOrgDeparts() {
        List<DepartModel> list = (List<DepartModel>) CacheService.get("sys.right.allorgdepts");
        return list;
    }
    
    /**
     * 取所有depart表数据（Map）
     *
     * @return
     */
    public static Map<String, DepartModel> getAllOrgDepartsMap() {
        Map<String, DepartModel> allorgdeptsmap = (Map<String, DepartModel>) CacheService.get("sys.right.allorgdeptsmap");
        return allorgdeptsmap;
    }
    
    /**
     * 取某一节点下的所有depart表数据
     *
     * @return
     */
    public static List<DepartModel> getAllOrgDepartsByOrgCode(String orgCode) {
        List<DepartModel> list = getAllOrgDeparts();
        
        String rootLevelId = getDepartByCode(orgCode).getLevelid();
        List<DepartModel> result = new ArrayList<DepartModel>();
        for (DepartModel model : list) {
            if (model.getLevelid().startsWith(rootLevelId)) {
                result.add(model);
            }
        }
        return result;
    }
    
    /**
     * 取某一单位的所有下级单位和部门
     * departType 1 仅单位，2 仅部门，3 混合
     *
     * @return
     */
    public static List<DepartModel> getSubDepartsByOrgCode(String departType, String orgCode) {
        List<DepartModel> list = getAllOrgDeparts();
        String rootLevelId = "";
        if (!"#".equals(orgCode)) {
            rootLevelId = getDepartByCode(orgCode).getLevelid();
        }
        
        List<DepartModel> result = new ArrayList<DepartModel>();
        for (DepartModel model : list) {
            if ("1".equals(departType)) {
                if ("1".equals(model.getDepart_type()) && model.getLevelid().startsWith(rootLevelId)) {
                    result.add(model);
                }
            } else if ("2".equals(departType)) {
                if (orgCode.equals(model.getOrg_code())) {
                    result.add(model);
                }
            } else {
                if (model.getLevelid() != null && model.getLevelid().startsWith(rootLevelId)) {
                    result.add(model);
                }
            }
        }
        return result;
    }
    
    /**
     * 取某一单位的所有部门信息并转化为ztree
     * departType  1 只检索单位，2 检索下级单位和部门
     *
     * @return
     */
    public static List<ZTreeNode> getDepartTreeByOrgCode(String departType, String orgCode) {
        List<DepartModel> list = getSubDepartsByOrgCode(departType, orgCode);
        
        boolean firstNodeSetOpen = false;
        List<ZTreeNode> result = new ArrayList<ZTreeNode>();
        for (DepartModel model : list) {
            ZTreeNode tree = new ZTreeNode();
            tree.setId(model.getDepart_id());
            tree.setName(model.getDepart_name());
            tree.setpId(model.getDepart_parent_code());
            tree.setNocheck(true);
            if (!firstNodeSetOpen) {
                tree.setOpen(true);
                firstNodeSetOpen = true;
            }
            result.add(tree);
        }
        return result;
    }
    
    /**
     * 取某一单位的人员信息
     *
     * @return
     */
    public static List<UserModel> getUsersByOrgCode(String departType, String orgCode) {
        Map<String, CacheUser> sysUsers = getSysUsers();
        Map<String, DepartModel> depts = getAllOrgDepartsMap();
        String levelId = depts.get(orgCode).getLevelid();
        
        List<UserModel> result = new ArrayList<UserModel>();
        for (CacheUser user : sysUsers.values()) {
            if ("admin".equals(user.getUser().getUser_id())) {
                continue;
            }
            if ("N".equalsIgnoreCase(user.getUser().getValidity()))
                continue;
            String userOrgLevelId = depts.get(user.getUser().getOrg_code()).getLevelid();
            if ("1".equals(departType)) {
                if (userOrgLevelId.startsWith(levelId)) {
                    result.add(user.getUser());
                }
            } else if ("2".equals(departType)) {
                if (orgCode.equals(user.getUser().getOrg_code())) {
                    result.add(user.getUser());
                }
            } else {
                if (userOrgLevelId != null && userOrgLevelId.startsWith(levelId)) {
                    result.add(user.getUser());
                }
            }
        }
        
        return result;
    }
    
    /**
     * 取某一单位的人员信息--转化为ztree
     *
     * @return
     */
    private static List<ZTreeNode> getUserTreeDataByOrgCode(String departType, String orgCode) {
        List<UserModel> list = getUsersByOrgCode(departType, orgCode);
        
        List<ZTreeNode> result = new ArrayList<ZTreeNode>();
        for (UserModel model : list) {
            ZTreeNode tree = new ZTreeNode();
            tree.setId(model.getUser_id());
            tree.setName(model.getUser_name());
            if ("1".equals(departType)) {
                tree.setpId(model.getOrg_id());
            } else {
                tree.setpId(model.getDepart_id());
            }
            
            result.add(tree);
        }
        return result;
    }
    
    /**
     * 取某一单位的人员树信息(树型结构)
     *
     * @return List<ZTreeNode>
     */
    public static List<ZTreeNode> getUsersTreeByOrgCode(String departType, String orgCode, String checked) {
        String rootPId = getDepartByCode(orgCode).getDepart_parent_code();
        List<ZTreeNode> list = getDepartTreeByOrgCode(departType, orgCode);
        //添加人员节点
        list.addAll(getUserTreeDataByOrgCode(departType, orgCode));
        //改造为树型结构
        List<ZTreeNode> result = TreeUtil.makeZTree(list, rootPId, checked);
        
        return result;
    }
    
    /**
     * 取某一单位的人员树信息
     *
     * @return
     */
    public static List<TreeObject> getEasyuiUsersTreeByOrgCode(String departType, String orgCode) {
        List<DepartModel> list = getSubDepartsByOrgCode(departType, orgCode);
        
        List<TreeObject> result = new ArrayList<TreeObject>();
        for (DepartModel model : list) {
            TreeObject to = new TreeObject();
            to.setId(model.getDepart_id());
            to.setParent_id(model.getDepart_parent_code());
            to.setText(model.getDepart_name());
            
            result.add(to);
        }
        
        return result;
    }
    
    /**
     * 菜单地址生成random
     *
     * @param entra 菜单入口地址
     * @return 添加random之后的地址
     */
    public static String getEntraWithRandom(String entra) {
        if (entra == null) {
            entra = "";
        } else {
            if (entra.startsWith("http://") || entra.startsWith("https://")) {
            } else {
                entra = SystemService.getBasePath() + entra;
            }
            if (entra.indexOf("?") >= 0) {
                entra += "&r=" + SystemService.getRadom();
            } else {
                entra += "?r=" + SystemService.getRadom();
            }
        }
        return entra;
    }
    
    /**
     * 取用户缓存数据
     */
    public static UserModel getUserByAccount(String account) {
        Map<String, CacheUser> sysUsers = getSysUserAccounts();
        
        CacheUser cacheUser = sysUsers.get(account);
        if (cacheUser != null) {
            return cacheUser.getUser();
        }
        return null;
    }
    
    /**
     * 通过用户id，获得用户的基本信息
     *
     * @param userId
     */
    public static UserModel getUserById(String userId) {
        Map<String, CacheUser> users = getSysUsers();
        CacheUser cu = users.get(userId);
        if (cu == null) {
            return null;
        } else {
            return cu.getUser();
        }
    }
}